'use strict'
const {Product,Op}=require('../model')
let fn_index = async(ctx,next)=>{
    let keyword = ctx.request.query.keyword
    if(keyword){
        let list = await Product.findAll({
            where:{
                [Op.or]:[
                    {id:isNaN(keyword)?0 : parseInt(keyword)},
                    {name:keyword},
                    {price:isNaN(keyword)?0 : parseInt(keyword)}
                ]
            }
        })

        ctx.body=list
    }else{
        let list = await Product.findAll({
            order:[['id','asc']]
        })
        ctx.body=list
    }
}
let fn_add = async(ctx,next)=>{
    let obj = ctx.request.body
    if(obj){
        let tmpobj ={
            name:obj.name,
            price:obj.price
        }
        await Product.create(tmpobj)
        ctx.body={
            code:1000,
            data:tmpobj,
            msg:'1'
        }
    }else{
        ctx.body={
            code:1000,
            data:'',
            msg:'1'
        }
    }
}
let fn_put = async(ctx,next)=>{
    let obj = ctx.request.body
    let id = ctx.request.params.id
    let product = await Product.findByPk(id)
    if(product){
        await Product.update(obj,{
            where:{
                id:id
            }
        })
        ctx.body={
            code:1000,
            data:obj,
            msg:'1'
        }
    }else{
        ctx.body={
            code:1000,
            data:'',
            msg:'1'
        }
    }
}
let fn_del = async(ctx,next)=>{
    let obj = ctx.request.body
    let id = ctx.request.params.id
    let product = await Product.findByPk(id)
    if(product){
        await Product.destroy({
            where:{
                id:id
            }
        })
        ctx.body={
            code:1000,
            data:{id:id},
            msg:'1'
        }
    }else{
        ctx.body={
            code:1000,
            data:'',
            msg:'1'
        }
    }
}
module.exports={
    'get /product':fn_index,
    'post /product':fn_add,
    'put /product/:id':fn_put,
    'delete /product/:id':fn_del,
}